package main

import (
	"encoding/json"
	"fmt"
	"gopkg.in/gcfg.v1"
	"log"
	"os"
	"tinp/common"
	"tinp/mylog"
	"tinp/server/gateway"
)

type Config struct {
	Gateway struct {
		Host      string
		Port      uint16
		ProxyFile string
	} `cfg:"gateway"`
}

var config Config

func init() {
	iniBytes, err := os.ReadFile("conf.ini")
	if err != nil {
		log.Fatalln("conf.ini 文件不存在!")
	}
	err = gcfg.ReadStringInto(&config, string(iniBytes))
	if err != nil {
		log.Fatalln(err)
	}
}

var proxyConfigs []*common.ProxyProtocol

func init() {
	bytes, err := os.ReadFile(config.Gateway.ProxyFile)
	if err != nil {
		log.Fatalf("%s 文件不存在!\n", config.Gateway.ProxyFile)
	}
	_ = json.Unmarshal(bytes, &proxyConfigs)
	if len(proxyConfigs) == 0 {
		log.Fatalln("代理配置为空!")
	}
}

func main() {
	sessionMgr := gateway.NewSessionManager()
	gateway2 := gateway.NewGateway(fmt.Sprintf("%s:%d", config.Gateway.Host, config.Gateway.Port), sessionMgr)
	go func() {
		log.Fatalln(gateway2.ListenAndServe())
	}()
	mylog.Logger.Infof("网关服务启动成功, 正在监听%d端口 ", config.Gateway.Port)

	for _, proxyConfig := range proxyConfigs {
		listener := gateway.NewListener(proxyConfig, sessionMgr)
		go func() {
			log.Fatalln(listener.ListenAndServe())
		}()
		mylog.Logger.Infof("正在监听%d端口, 客户端ID为: %s ", proxyConfig.ListenPort, proxyConfig.ClientId)
	}
	select {}
}
